import { setToken, removeToken } from '../../utils/auth'
import setting from '../../settings'
import {
  loginApi,
  logoutApi,
  userProfileApi,
  updatePwdApi,
  updateUserProfileApi,
  userMenuApi,
  userSettingApi
} from '../../api/authApi'

export default {
  state: {
    user: null,
    token: null,
    menu: [],
    roles: [],
    permissions: [],
    userSetting: {},
    isAdmin: false
  },
  mutations: {
    setUserProfile: (state, data) => {
      state.user = data
    },
    setUserRole: (state, data) => {
      state.roles = data
      state.isAdmin = data.indexOf(setting.superAdminRole) > -1
    },
    initMenu: (state, data) => {
      state.menu = data
    },
    setUserPermission: (state, data) => {
      state.permissions = data
    },
    setUserSetting: (state, data) => {
      state.userSetting = data
    }
  },
  actions: {
    login: ({ commit }, params) => {
      return new Promise((resolve, reject) => {
        loginApi(params).then((res) => {
          setToken(res.data.access_token, { expires: new Date(Date.now() + res.data.expires_in * 1000) })
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    logout: ({ commit }, params) => {
      return logoutApi(params).then((res) => {
        removeToken()
        commit('setUserProfile', {})
        commit('setUserRole', [])
        commit('initMenu', [])
        commit('setUserPermission', [])
      }).catch(() => {
        removeToken()
        commit('setUserProfile', {})
        commit('setUserRole', [])
        commit('initMenu', [])
        commit('setUserPermission', [])
      })
    },
    getUserProfile: ({ commit }, parmas) => {
      return new Promise((resolve, reject) => {
        userProfileApi(parmas).then((res) => {
          const data = res.data && (res.data.data || res.data)
          if (data) {
            commit('setUserProfile', data.user)
            commit('setUserRole', data.role)
            commit('setUserPermission', data.permission)
          } else {
            console.log('刚获取的用户信息为空')
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    updatePasswd ({ commit }, params) {
      return updatePwdApi(params)
    },
    updateUserProfile ({ commit }, params) {
      return updateUserProfileApi(params)
    },
    getMenu: ({ commit }, params) => {
      return new Promise((resolve, reject) => {
        userMenuApi(params).then((res) => {
          const data = res.data && (res.data.data || res.data)
          commit('initMenu', data && data.length ? data : [])
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    getUserSettings: ({ commit }, params) => {
      return userSettingApi(params).then((res) => {
        commit('setUserSetting', res.data)
      })
    }
  }
}
